<template>
  <div class="user-management">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span class="title">用户管理</span>
          <div class="header-actions">
            <el-button 
              type="primary" 
              :icon="Plus" 
              @click="handleAddUser"
              :loading="addingUser"
            >
              添加用户
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="search-filter">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名/邮箱/角色"
          prefix-icon="el-icon-Search"
          clearable
          @input="handleSearch"
          class="search-input"
        />
        <el-select
          v-model="roleFilter"
          placeholder="筛选角色"
          clearable
          @change="handleSearch"
          class="role-filter"
        >
          <el-option label="管理员" value="admin" />
          <el-option label="普通用户" value="user" />
          <el-option label="审计员" value="auditor" />
        </el-select>
      </div>

      <!-- 用户列表 -->
      <el-table
        v-loading="loading"
        :data="filteredUsers"
        style="width: 100%"
        border
        stripe
        fit
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="row => !row.systemUser"
        />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="username" label="用户名" width="180">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="32" :src="getUserAvatar(row)">
                {{ getUserNameInitial(row) }}
              </el-avatar>
              <span class="username">{{ row.username }}</span>
              <el-tag 
                v-if="row.systemUser" 
                type="info" 
                size="small"
                class="system-tag"
              >
                系统用户
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="用户姓名" width="150" />
        <el-table-column prop="email" label="邮箱" width="220" />
        <el-table-column prop="role" label="角色" width="120">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)" size="small">
              {{ getRoleName(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="active"
              inactive-value="inactive"
              @change="handleStatusChange(row)"
              :disabled="row.systemUser || updatingUsers.has(row.id)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="180" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.lastLoginTime ? formatDate(row.lastLoginTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                link 
                @click="handleEditUser(row)"
                :disabled="row.systemUser || updatingUsers.has(row.id)"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                link 
                @click="handleDeleteUser(row)"
                :disabled="row.systemUser || updatingUsers.has(row.id) || isCurrentUser(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingUser.id ? '编辑用户' : '添加用户'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="userFormRef"
        :model="editingUser"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editingUser.username" placeholder="请输入用户名" :disabled="editingUser.id" />
        </el-form-item>
        <el-form-item label="用户姓名" prop="name">
          <el-input v-model="editingUser.name" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editingUser.email" type="email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editingUser.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
            <el-option label="审计员" value="auditor" />
          </el-select>
        </el-form-item>
        <el-form-item 
          v-if="!editingUser.id" 
          label="初始密码" 
          prop="password"
        >
          <el-input
            v-model="editingUser.password"
            type="password"
            placeholder="请输入初始密码"
            show-password
          />
        </el-form-item>
        <el-form-item 
          v-if="!editingUser.id"
          label="确认密码" 
          prop="confirmPassword"
        >
          <el-input
            v-model="editingUser.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editingUser.status">
            <el-radio value="active">启用</el-radio>
            <el-radio value="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :loading="savingUser"
        >
          {{ savingUser ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPasswordVisible"
      title="重置密码"
      width="400px"
      destroy-on-close
    >
      <el-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="resetPasswordRules"
        label-width="80px"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="resetPasswordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="resetPasswordForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetPasswordVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleResetPassword"
          :loading="resettingPassword"
        >
          {{ resettingPassword ? '重置中...' : '确认重置' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 批量操作确认对话框 -->
    <el-dialog
      v-model="batchDeleteVisible"
      title="批量删除"
      width="400px"
      destroy-on-close
    >
      <p class="warning-message">
        确定要删除选中的 <strong>{{ selectedUsers.length }}</strong> 个用户吗？此操作不可撤销。
      </p>
      <template #footer>
        <el-button @click="batchDeleteVisible = false">取消</el-button>
        <el-button 
          type="danger" 
          @click="handleBatchDelete"
          :loading="batchDeleting"
        >
          {{ batchDeleting ? '删除中...' : '确认删除' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, User } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import apiService from '../../services/apiService.js'

const router = useRouter()
const route = useRoute()

// 状态管理
const loading = ref(false)
const addingUser = ref(false)
const savingUser = ref(false)
const updatingUsers = ref(new Set())
const resettingPassword = ref(false)
const batchDeleting = ref(false)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 搜索和筛选
const searchQuery = ref('')
const roleFilter = ref('')

// 对话框控制
const dialogVisible = ref(false)
const resetPasswordVisible = ref(false)
const batchDeleteVisible = ref(false)

// 用户表单引用
const userFormRef = ref(null)
const resetPasswordFormRef = ref(null)

// 选择的数据
const selectedUsers = ref([])

// 表格数据
const users = ref([])

// 当前编辑用户
const editingUser = reactive({
  id: '',
  username: '',
  name: '',
  email: '',
  role: 'user',
  status: 'active',
  password: '',
  confirmPassword: ''
})

// 重置密码表单
const resetPasswordForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入用户姓名', trigger: 'blur' },
    { min: 2, max: 30, message: '用户姓名长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为 6 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        // 增强密码强度要求
        const hasLower = /[a-z]/.test(value)
        const hasUpper = /[A-Z]/.test(value)
        const hasNumber = /[0-9]/.test(value)
        const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(value)
        
        const strengthCount = [hasLower, hasUpper, hasNumber, hasSpecial].filter(Boolean).length
        
        if (strengthCount < 2) {
          callback(new Error('密码强度太弱，建议包含多种字符类型'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== editingUser.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 重置密码验证规则
const resetPasswordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为 6 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        // 增强密码强度要求
        const hasLower = /[a-z]/.test(value)
        const hasUpper = /[A-Z]/.test(value)
        const hasNumber = /[0-9]/.test(value)
        const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(value)
        
        const strengthCount = [hasLower, hasUpper, hasNumber, hasSpecial].filter(Boolean).length
        
        if (strengthCount < 2) {
          callback(new Error('密码强度太弱，建议包含多种字符类型'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetPasswordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性：过滤后的用户列表
const filteredUsers = computed(() => {
  let result = [...users.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(user => 
      user.username.toLowerCase().includes(query) ||
      user.name.toLowerCase().includes(query) ||
      user.email.toLowerCase().includes(query) ||
      getRoleName(user.role).toLowerCase().includes(query)
    )
  }
  
  // 角色过滤
  if (roleFilter.value) {
    result = result.filter(user => user.role === roleFilter.value)
  }
  
  // 更新总数
  total.value = result.length
  
  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

// 获取当前用户
const getCurrentUser = () => {
  const userStr = localStorage.getItem('user')
  return userStr ? JSON.parse(userStr) : null
}

// 判断是否为当前用户
const isCurrentUser = (user) => {
  const currentUser = getCurrentUser()
  return currentUser && currentUser.id === user.id
}

// 获取用户头像
const getUserAvatar = (user) => {
  // 在实际应用中，这里可能会返回真实的头像URL
  // 这里简单返回空，使用用户名首字母作为头像
  return ''
}

// 获取用户名首字母
const getUserNameInitial = (user) => {
  return user.name ? user.name.charAt(0).toUpperCase() : user.username.charAt(0).toUpperCase()
}

// 获取角色名称
const getRoleName = (role) => {
  const roleMap = {
    'admin': '管理员',
    'user': '普通用户',
    'auditor': '审计员'
  }
  return roleMap[role] || role
}

// 获取角色类型（用于标签样式）
const getRoleType = (role) => {
  const typeMap = {
    'admin': 'danger',
    'user': 'primary',
    'auditor': 'warning'
  }
  return typeMap[role] || 'info'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 加载用户数据
const loadUsers = async () => {
  try {
    loading.value = true
    
    if (apiService.useMockData?.value) {
      // 模拟数据
      users.value = [
        {
          id: 1,
          username: 'admin',
          name: '系统管理员',
          email: 'admin@example.com',
          role: 'admin',
          status: 'active',
          systemUser: true,
          createdAt: '2023-01-01T00:00:00Z',
          lastLoginTime: new Date().toISOString()
        },
        {
          id: 2,
          username: 'user1',
          name: '测试用户1',
          email: 'user1@example.com',
          role: 'user',
          status: 'active',
          systemUser: false,
          createdAt: '2023-01-02T00:00:00Z',
          lastLoginTime: '2024-01-10T14:30:00Z'
        },
        {
          id: 3,
          username: 'auditor1',
          name: '安全审计员',
          email: 'auditor1@example.com',
          role: 'auditor',
          status: 'active',
          systemUser: false,
          createdAt: '2023-01-03T00:00:00Z',
          lastLoginTime: '2024-01-09T09:15:00Z'
        },
        {
          id: 4,
          username: 'user2',
          name: '测试用户2',
          email: 'user2@example.com',
          role: 'user',
          status: 'inactive',
          systemUser: false,
          createdAt: '2023-01-04T00:00:00Z',
          lastLoginTime: null
        }
      ]
    } else {
      // 实际API调用
      const response = await apiService.getUsers()
      users.value = response.data || []
    }
  } catch (error) {
    console.error('加载用户失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
}

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1 // 重置到第一页
}

// 处理当前页变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 重置用户表单
const resetUserForm = () => {
  Object.assign(editingUser, {
    id: '',
    username: '',
    name: '',
    email: '',
    role: 'user',
    status: 'active',
    password: '',
    confirmPassword: ''
  })
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 处理添加用户
const handleAddUser = () => {
  resetUserForm()
  dialogVisible.value = true
}

// 处理编辑用户
const handleEditUser = (user) => {
  // 复制用户数据到编辑表单
  Object.assign(editingUser, {
    id: user.id,
    username: user.username,
    name: user.name,
    email: user.email,
    role: user.role,
    status: user.status
  })
  dialogVisible.value = true
}

// 处理删除用户
const handleDeleteUser = (user) => {
  if (user.systemUser) {
    ElMessage.warning('系统用户不能删除')
    return
  }
  
  if (isCurrentUser(user)) {
    ElMessage.warning('不能删除当前登录用户')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除用户「${user.username}」吗？此操作不可撤销。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  .then(async () => {
    try {
      updatingUsers.value.add(user.id)
      
      if (apiService.useMockData?.value) {
        // 模拟删除
        const index = users.value.findIndex(u => u.id === user.id)
        if (index > -1) {
          users.value.splice(index, 1)
        }
      } else {
        // 实际API调用
        await apiService.deleteUser(user.id)
      }
      
      ElMessage.success('用户删除成功')
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    } finally {
      updatingUsers.value.delete(user.id)
    }
  })
  .catch(() => {
    // 取消删除
  })
}

// 处理批量删除
const handleBatchDelete = async () => {
  try {
    batchDeleting.value = true
    
    const userIds = selectedUsers.value.map(user => user.id)
    
    if (apiService.useMockData?.value) {
      // 模拟批量删除
      users.value = users.value.filter(user => !userIds.includes(user.id))
    } else {
      // 实际API调用
      await apiService.batchDeleteUsers(userIds)
    }
    
    ElMessage.success(`成功删除 ${selectedUsers.value.length} 个用户`)
    selectedUsers.value = []
    batchDeleteVisible.value = false
  } catch (error) {
    console.error('批量删除用户失败:', error)
    ElMessage.error('批量删除用户失败')
  } finally {
    batchDeleting.value = false
  }
}

// 处理状态变更
const handleStatusChange = async (user) => {
  try {
    updatingUsers.value.add(user.id)
    
    if (apiService.useMockData?.value) {
      // 模拟更新状态
      // 状态已经通过v-model更新，这里不需要额外操作
    } else {
      // 实际API调用
      await apiService.updateUserStatus(user.id, user.status)
    }
    
    ElMessage.success(`用户「${user.username}」状态更新成功`)
  } catch (error) {
    console.error('更新用户状态失败:', error)
    ElMessage.error('更新用户状态失败')
    // 恢复原状态
    user.status = user.status === 'active' ? 'inactive' : 'active'
  } finally {
    updatingUsers.value.delete(user.id)
  }
}

// 处理提交表单
const handleSubmit = async () => {
  if (!userFormRef.value || !userFormRef.value.validate()) {
    return
  }
  
  try {
    savingUser.value = true
    
    const userData = {
      username: editingUser.username,
      name: editingUser.name,
      email: editingUser.email,
      role: editingUser.role,
      status: editingUser.status
    }
    
    // 只有新增用户时才包含密码
    if (!editingUser.id) {
      userData.password = editingUser.password
    }
    
    let result
    
    if (apiService.useMockData?.value) {
      // 模拟API调用
      if (editingUser.id) {
        // 更新用户
        const index = users.value.findIndex(u => u.id === editingUser.id)
        if (index > -1) {
          users.value[index] = { ...users.value[index], ...userData }
        }
      } else {
        // 添加用户
        const newUser = {
          ...userData,
          id: Date.now(),
          systemUser: false,
          createdAt: new Date().toISOString(),
          lastLoginTime: null
        }
        users.value.push(newUser)
      }
    } else {
      // 实际API调用
      if (editingUser.id) {
        result = await apiService.updateUser(editingUser.id, userData)
      } else {
        result = await apiService.createUser(userData)
      }
    }
    
    ElMessage.success(editingUser.id ? '用户更新成功' : '用户创建成功')
    dialogVisible.value = false
    
    // 重置表单
    resetUserForm()
  } catch (error) {
    console.error('保存用户失败:', error)
    ElMessage.error(editingUser.id ? '用户更新失败' : '用户创建失败')
  } finally {
    savingUser.value = false
  }
}

// 处理重置密码
const handleResetPassword = async () => {
  if (!resetPasswordFormRef.value || !resetPasswordFormRef.value.validate()) {
    return
  }
  
  try {
    resettingPassword.value = true
    
    const userId = editingUser.id
    const { newPassword } = resetPasswordForm
    
    if (apiService.useMockData?.value) {
      // 模拟重置密码
      ElMessage.success('密码重置成功')
    } else {
      // 实际API调用
      await apiService.resetUserPassword(userId, newPassword)
    }
    
    ElMessage.success('密码重置成功')
    resetPasswordVisible.value = false
    
    // 重置表单
    Object.assign(resetPasswordForm, {
      newPassword: '',
      confirmPassword: ''
    })
  } catch (error) {
    console.error('重置密码失败:', error)
    ElMessage.error('密码重置失败')
  } finally {
    resettingPassword.value = false
  }
}

// 监听搜索和筛选条件变化
watch([searchQuery, roleFilter], handleSearch)

// 组件挂载时加载数据
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-card {
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.search-filter {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.role-filter {
  width: 180px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.username {
  font-weight: 500;
}

.system-tag {
  margin-left: auto;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.warning-message {
  color: #606266;
  line-height: 1.6;
}

.warning-message strong {
  color: #f56c6c;
  font-size: 16px;
}

@media (max-width: 768px) {
  .user-management {
    padding: 10px;
  }
  
  .search-filter {
    flex-direction: column;
  }
  
  .search-input,
  .role-filter {
    width: 100%;
  }
  
  .pagination-wrapper {
    justify-content: center;
  }
}
</style>